<template>
  <!-- 确认退药 -->
  <div class="app-container">
    <el-row class="div-height-left">
      <el-col :span="8">
        <div class="search-container">
          <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
            <el-form-item :label="inoroutFlag === 4 ? '门诊号' : '住院号'" prop="clinicNo">
              <el-input v-model="queryParams.clinicNo" :disabled="queryParams.clinicId != ''"
                        :placeholder="inoroutFlag === 4 ? '请输入门诊号' : '请输入住院号'"
                        clearable style="width: 160px;"/>
            </el-form-item>
            <el-form-item label="退药日期">
              <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                              range-separator="截止"
                              start-placeholder="开始日期" style="width: 320px;" type="daterange"
                              @change="timeChange"></el-date-picker>
            </el-form-item>
            <el-form-item label="领药人姓名" prop="name">
              <el-input v-model="queryParams.name" :disabled="queryParams.clinicId != ''" clearable
                        placeholder="请输入领药人姓名" style="width: 160px;"/>
            </el-form-item>
            <el-form-item label="处方号" prop="applyNo">
              <el-input v-model="queryParams.applyNo" :disabled="queryParams.clinicId != ''" clearable
                        placeholder="请输入处方号" style="width: 160px;"/>
            </el-form-item>
            <el-row>
              <div class="mr20" style="float: right">
                <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
                <!--                <el-button :disabled="ids.length <= 0" plain style="margin-left: 12px;" type="danger"-->
                <!--                           @click="issuedFillOutTraceabilityCode">-->
                <!--                  <i-ep-edit/>-->
                <!--                  填写追溯码-->
                <!--                </el-button>-->
              </div>
            </el-row>
          </el-form>
        </div>
        <el-table ref="applyTableRef" v-adaptive="adaptiveHeight" :border="true" :data="prescriptionApplyList"
                  :header-cell-style="$headerCellStyle"
                  :stripe="true" highlight-current-row @row-click="rowClick"
                  @selection-change="handleSelectionChange">
          <el-table-column :align="'left'" fixed="left" type="selection" width="40"/>
          <el-table-column :align="'left'" label="领药人信息" prop="name" width="130">
            <template #default="scope">
              {{ scope.row.name }}
              <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
              {{ scope.row.age }} 岁{{ scope.row.ageMonth }} 月
              <!-- {{ scope.row.ageDay }}天 -->
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="门诊号" prop="clinicNo"
                           width="100"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方号" prop="applyNo"
                           width="100"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方属性" prop="prescAttr"
                           width="80">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['prescription_type']" :value="scope.row.prescAttr"/>
            </template>
          </el-table-column>
          <!-- <el-table-column :align="'center'" label="处方分类" prop="itemClass" width="70"
                  :show-overflow-tooltip="true">
                  <template #default="scope">
                      <dict-data-tag :options="dictDataMap['bill_item_class_dict']"
                          :value="scope.row.itemClass" />
                  </template>
              </el-table-column> -->
          <el-table-column :align="'center'" label="开单科室" prop="applyDeptName"/>
          <el-table-column :align="'center'" label="开单时间" prop="createTime" width="130"/>
          <!-- <el-table-column :align="'center'" label="发药药房" prop="implementDepName" /> -->
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                           width="80"/>
        </el-table>
        <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                    @pagination="getList"/>
      </el-col>
      <el-col :span="16" class="div-height-left">
        <el-empty v-if="ids.length <= 0" description="暂无数据，请勾选左侧处方列表后，再操作。"/>
        <div v-else class="div-height-left">
          <div :style="{height: (queryParams.clinicId != '' ? '350px' : '64%'), overflowY: 'auto'}"
               class="mb10">
            <template v-for="(map, index) in itemMap">
              <div class="search-container" style="padding: 5px 0 10px 10px">
                <span class="ys-css">{{ map.key }}</span>
                <el-table :border="true" :data="map.prescriptionItemVoList"
                          :header-cell-style="$headerCellStyle"
                          :stripe="true" highlight-current-row>
                  <el-table-column :align="'center'" label="收费状态" prop="chargeFlag" width="140px">
                    <template #default="scope">
                      <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                                     :value="scope.row.chargeFlag"/>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="组号" prop="groupNumber" width="60">
                    <template #default="scope">
                      <span>{{ scope.row.groupNumber }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="药品" prop="drugName">
                    <template #default="scope">
                      <span>{{ scope.row.drugName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="途径" prop="channel" width="100">
                    <template #default="scope">
                      <span>{{ scope.row.channelName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="单次用量" prop="singleDosage" width="120">
                    <template #default="scope">
                                        <span style="margin-left: -15px"> {{
                                            parseFloat(scope.row.singleDosage).toFixed(2)
                                          }}<dict-data-tag
                                            :options="dictDataMap['dose_unit']" :value="scope.row.singleUnit"
                                            style="margin: -23px -20px 0px 35px"/></span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="频次" prop="performFreq"
                                   width="110">
                    <template #default="scope">
                      <span>{{ scope.row.performFreqName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="天数" prop="abidance" width="60">
                    <template #default="scope">
                      <span>{{ scope.row.abidance }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="数量" prop="num" width="90">
                    <template #default="scope">
                      <span class="ys-css">{{ scope.row.num }}</span> <span><dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.packSize === '1' ?
                                                    scope.row.minUnits : scope.row.packageUnits"
                      style="margin: -23px -20px 0px 27px"/></span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格"
                                   prop="packageSpec"
                                   width="160">
                    <template #default="scope">
                      <span class="ys-css">{{ scope.row.packageSpec }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                                   width="110px"/>
                  <el-table-column :align="'center'" label="单价" prop="price" width="95">
                    <template #default="scope">
                      {{ scope.row.price }}元
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="总价" prop="sumPrice" width="80">
                    <template #default="scope">
                      {{ parseFloat(scope.row.sumPrice).toFixed(2) }}元
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="免皮试" prop="noSkin" width="60px">
                    <template #default="scope">
                                        <span>
                                            <dict-data-tag :options="dictDataMap['sys_yes_no']"
                                                           :value="scope.row.noSkin"/>
                                        </span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="滴速" :align="'center'" width="110px" prop="dripSpeed">
                      <template #default="scope">
                          <span><dict-data-tag :options="dictDataMap['sys_drop_speed']"
                                  :value="scope.row.dripSpeed" /></span>
                      </template>
                  </el-table-column> -->
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="医生说明"
                                   width="120px">
                    <template #default="scope">
                      <span>{{ scope.row.remarks }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" label="发放明细" prop="moneyType" width="70">
                    <template #default="scope">
                      <el-popover :width="800" placement="left"
                                  title="发放明细"
                                  trigger="hover">
                        <template #reference>
                          <el-button type="primary">详情</el-button>
                        </template>
                        <el-table :border="true" :data="scope.row.drugStockAllLog" :header-cell-style="$headerCellStyle"
                                  :stripe="true" height="200"
                                  highlight-current-row>
                          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="流转类型"
                                           prop="recordType"
                                           width="70px">
                            <template #default="scope">
                              {{ scope.row.recordType }}
                            </template>
                          </el-table-column>
                          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="来源类型"
                                           prop="sourceType"/>
                          <el-table-column :align="'left'" :show-overflow-tooltip="true" label="药品名称"
                                           min-width="190px" prop="drugName">
                            <template #default="scope">
                              <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
                            </template>
                          </el-table-column>
                          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂商名称"
                                           prop="firmName" width="120px"/>
                          <el-table-column :align="'right'" :show-overflow-tooltip="true" label="数量" prop="amount">
                            <template #default="scope">
                              <span class="ys-css">{{ scope.row.amount }}</span>{{ scope.row.units }}
                            </template>
                          </el-table-column>
                          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号"
                                           prop="batchNo"/>
                        </el-table>
                      </el-popover>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </div>
          <span class="ml10">药品汇总</span>
          <div :style="{height: (queryParams.clinicId != '' ? 'calc(100% - 350px)' : '33%'),
                    overflowY: 'auto'}" class="ml10">
            <el-table :border="true" :data="prescriptionItemSummary" :header-cell-style="$headerCellStyle"
                      :stripe="true" :summary-method="summarySum"
                      highlight-current-row
                      show-summary>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品"
                               prop="drugName"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码"
                               prop="drugCode"
                               width="180"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格"
                               prop="packageSpec"
                               width="130"/>
              <el-table-column :align="'center'" :show-overflow-tooltip="true" label="数量" prop="num"
                               width="130">
                <template #default="scope">
                  <template v-if="scope.row.quantityMin > 0">
                    <!--小包装-->
                    <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">
                      {{ scope.row.quantityMin }}
                    </div>
                  </template>
                  <!--大包装-->
                  <template v-if="scope.row.quantityMax > 0">
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.packageUnits"
                                   style="float: right"/>
                    <div style="float: right;margin-right: 5px;font-weight: bold;">{{
                        scope.row.quantityMax
                      }}
                    </div>
                  </template>
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="单价" prop="price" width="130">
                <template #default="scope">
                  {{ scope.row.price }}元
                </template>
              </el-table-column>
              <el-table-column :align="'center'" label="总价" prop="sumPrice" width="130">
                <template #default="scope">
                  {{ parseFloat(scope.row.sumPrice).toFixed(2) }}元
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
      <traceability-code ref="traceabilityCodeRef" :org-id="queryParams.orgId" @submit-form-ok="submitFormOk"/>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";
import {selectPagePrescriptionApply} from "@/api/patient/prescriptionApply.ts";
import {issuedGrantInfoOk, listPrescriptionItemMap} from "@/api/patient/prescriptionItem.ts";

const dictStore = useDictStoreHook();
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
let dictDataMap = ref(dictStore.isTypeGetData('prescription_type', 'drug_classification', 'bill_item_class_dict', 'sys_user_sex',
  'dose_unit', 'spec_unit', 'sys_yes_no', 'sys_drop_speed', 'charge_flag_dict'))
const inoroutFlag = ref(4)
const emits = defineEmits(["convenientIssuedGrantOk"])
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const props = defineProps({
  adaptiveHeight: {
    type: Number,
    default: 320,
  },
  // 医保-药品销售、入库追溯码是否必填 Y 必填 N不必填
  medicalInsuranceTraceabilityCode: {
    type: String,
    default: 'N'
  },
})
const traceabilityCodeRef = ref()
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: userInfo.orgId,
  implementDept: currentSelectDept,
  confirmFlag: "3",
  confirmFlagArray: [],
  inoroutFlag: inoroutFlag.value,
  clinicId: ''
  // chargeFlag: "6"
})
const applyTableRef = ref()
const queryParamsRef = ref()

// 主记录列表
const prescriptionApplyList = ref<any>([])
const itemMap = ref<any>([])
// 药品汇总列表
const prescriptionItemSummary = ref<any>([])
const total = ref(0);
const ids = ref([])

/** 搜索 */
function handleQuery() {
  getList()
}

/** 重置 */
function resetQuery() {
  queryParams.value.name = ""
  queryParams.value.clinicNo = ""
  queryParams.value.applyNo = ""
  getList()
}

/** 处方列表 行点击事件 */
function rowClick(row: any) {
  applyTableRef.value.toggleRowSelection(row);
}

/** 查询处方主记录 */
function getList() {
  if (!queryParams.value.implementDept) {
    return ElMessage.error("请先选择发药药房，再进行发药查询操作。");
  }
  // 是否从药房 -已退药记录
  queryParams.value.isConfirm = 1
  selectPagePrescriptionApply(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    prescriptionApplyList.value = response.rows;
    total.value = response.total;
  });
}

function timeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/** 查询子列表map */
function listPrescriptionItemMapFun() {
  if (ids.value.length > 0) {
    listPrescriptionItemMap({
      applyIds: ids.value,
      orgId: queryParams.value.orgId,
      inoroutFlag: queryParams.value.inoroutFlag,
      confirmFlag: queryParams.value.confirmFlag,
    }).then((res: resType) => {
      itemMap.value = res.data?.list
      prescriptionItemSummary.value = res.data?.summary
      prescriptionItemSummary.value.forEach(item => {
        item.quantityMax = Math.floor(item.num / item.packageNum)
        item.quantityMin = item.num % item.packageNum
      })
    })
  } else {
    itemMap.value = []
  }

}

/** 勾选 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.applyId);
  listPrescriptionItemMapFun()
}

/** 确认退药 */
function issuedGrantInfoOkFun(row: any) {
  ElMessageBox.confirm("确定要退药吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    issuedGrantInfoOk({applyId: row.applyId, orgId: row.orgId}).then((res: resType) => {
      if (res.code === 200) {
        ElMessage.success("退药成功");
        emits("convenientIssuedGrantOk")
        getList()
        itemMap.value = []
      }
    })
  })
}

// 合计列
function summarySum({columns, data}) {
  const sums: any = [];
  columns.forEach((column, index) => {
    const values = data.map((item) => {
      return Number(item["sumPrice"]);
    });
    if (index === 0) {
      sums[index] = "合计"; //可更改合计行的名称
      return;
    }
    if (index === 5) {
      let sumPrice: number = 0.00;
      values.forEach(item => {
        sumPrice += item
      })
      sums[index] = sumPrice.toFixed(2) + "元"; //给合计项添加单位%
    }
  })
  return sums;
}


/**
 * 便捷门诊打开初始化函数
 * @param clinicId
 * @param implementDept
 */
function initQuery(clinicId: String, implementDept: String) {
  queryParams.value.clinicId = clinicId
  queryParams.value.implementDept = implementDept
  handleQuery()
}

function issuedFillOutTraceabilityCode() {
  nextTick(() => {
    const obj = {
      ids: ids.value,
      // 发药 1 ； 医嘱摆药 2
      type: "1"
    }
    traceabilityCodeRef.value.initOpenTraceabilityCode(obj)
  })
}

defineExpose({
  initQuery,
  handleQuery
})

</script>
